﻿#include <iostream>
#include <functional>
#include <thread>
#include <future>
using namespace std;

#include "threadpool.h"

/*
如何使线程池提交任务更加方便
1.pool.submitTask(sum1, 10, 20);
  pool.submitTask(sum2, 10, 20, 30);
  -> submitTask - 可变参模板编程

2.为了接收返回值，构建了Result及相关的类型，代码冗余
  C++11 线程库 thread packaged_task(function函数对象) async
  使用future来代替Result，来节省线程池的代码
*/

int sum1(int a, int b)
{
    this_thread::sleep_for(chrono::seconds(2));
    return a + b;
}
int sum2(int a, int b, int c)
{
    this_thread::sleep_for(chrono::seconds(2));
    return a + b + c;
}

int main()
{
#if 0
    packaged_task<int(int, int)> task(sum1);
    // future <=> Result
    future<int> res = task.get_future();
    // task(10, 20);
    thread t(std::move(task), 10, 20);
    t.detach();

    cout << res.get() << endl;
    /*thread t1(sum1, 10, 20);
    thread t2(sum2, 1, 2, 3);

    t1.join();
    t2.join();*/

#endif
    ThreadPool pool;
    // pool.setMode(PoolMode::MODE_CACHED); // 设置线程池工作模式
    // pool.setThreadSizeThresHold(1024) // cached模式下可以设定线程最大数量

    pool.setTaskQueMaxThresHold(2); // 设置任务队列上限阈值

    pool.start(2);

    // C++11的future
    future<int> r1 = pool.submitTask(sum1, 1, 2);
    future<int> r2 = pool.submitTask(sum2, 1, 2, 3);
    future<double> r3 = pool.submitTask([](int b, int e)->double {
        int sum = 0;
        for (int i = b; i <= e; i++)
            sum += i;
        return sum;
        }, 1, 100);
    future<double> r4 = pool.submitTask([](int b, int e)->double {
        int sum = 0;
        for (int i = b; i <= e; i++)
            sum += i;
        return sum;
        }, 1, 100);
    future<double> r5 = pool.submitTask([](int b, int e)->double {
        int sum = 0;
        for (int i = b; i <= e; i++)
            sum += i;
        return sum;
        }, 1, 100);

    cout << r1.get() << endl;
    cout << r2.get() << endl;
    cout << r3.get() << endl;
    cout << r4.get() << endl;
    cout << r5.get() << endl;

    return 0;
}
